package com.example.user.config;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * \* @author: bear
 * \* Date: 2022-04-10-18:46
 * \* describe:
 */
@Component
@Order(-1)
public class Myfilter implements Filter {


	@Resource
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		StringBuffer requestURL = request.getRequestURL();
		String path = requestURL.substring(requestURL.indexOf("8763/") + 4);
		if(path.equals("/getRedis")){
			filterChain.doFilter(servletRequest,servletResponse);
			return;
		}
		String value="";
		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies) {
			if(cookie.getName().equals("token")){
				value = cookie.getValue();
			}
		}
		String value11 = stringRedisTemplate.opsForValue().get(value);
		if(value11 == null){
			throw new RuntimeException("未登录");
		}
		filterChain.doFilter(servletRequest,servletResponse);
		return;
	}

	@Override
	public void destroy() {

	}
}
